package com.stadium.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.stadium.common.BaseResponse;
import com.stadium.common.config.security.TokenAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Administrator on 2017/11/14.
 */
public class JWTAuthenticationFilter extends GenericFilterBean {
    @Autowired
    TokenAuthentication tokenAuthentication;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException {
        try {
            Authentication authentication = tokenAuthentication.authToken((HttpServletRequest) request, (HttpServletResponse) response);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            //重置response
            response.reset();
            //设置编码格式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            ((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", "*");
            PrintWriter pw = response.getWriter();
            pw.append(JSONObject.toJSONString(BaseResponse.error("登陆状态失效，请重新登陆")));
            pw.flush();
            pw.close();
        }
    }
}
